
<html>
<head><title>Calculator</title></head>
<body>

<h1>Calculator</h1>
by Alexander Chow<br />
Type an expression in the following box (e.g. 10.5+20*3/25).
<p>
<form action="calculator.php" method="GET">
<input type="text" name="expr"><input type="submit" value="Calculate">
</form>
</p>

<?php

$expr = $_GET["expr"];
if ($expr) {
    echo "<h2>Result</h2>";
    
    // Check if expression is valid
    if (preg_match('/^(?:\s*\-?\s*[0-9]+(?:\.[0-9]*)?)(?:\s*[+*\-\/]\s*\-?\s*[0-9]+(?:\.[0-9]*)?)*\s*$/', $expr) && !preg_match("/\-\-/", $expr)) {
        @eval("\$result = $expr;");
        echo "<pre>$expr = $result</pre>";
    }
    else {
        echo "<pre>Invalid expression: $expr</pre>";
    }
}

?>

</body>
</html>

